<?php
/**
 * Create By: PhpStorm
 * User: yihua
 * File: Login.php
 * Date: 2017/1/8
 * Time: 22:46
 */
namespace app\home\model\page;

use app\api\model\dao\Admin;
use app\library\Common;
use app\library\CommonConfig;
use app\library\Error;
use app\library\PageBase;
use think\Cache;
use think\Cookie;
use think\Request;
use think\Session;
use think\Validate;

class Login extends PageBase
{
    private $objAdmin;

    public function __construct()
    {
        parent::__construct();
        $this->objAdmin = new Admin();
    }

    public function excute($param)
    {
        /*
        if(!Cookie::has('MSPASS')){
        }
        Cookie::set('MSPASS',Common::getToken(),['expire'=>60*30,]);
        Cookie::set(CommonConfig::COOKIE_TYPE,Common::getToken(),['expire'=>60*30,]);
        $this->data[0]= Request::instance()->cookie();
        */
        $ret = $this->checkParam($param);
        if ($ret) {
            return $this->getRes(Error::ERR_PARAM, $ret);
        }
        $conds = [
            'user_name' => $param['username'],
        ];
        $data = $this->objAdmin->getAdminByConds($conds, []);
        if (empty($data)) {
            return $this->getRes(Error::ERR_SUCCESS, '用户不存在');
        }
        $param['password'] = md5($param['password']);
        if ($param['password'] == $data[0]['passwd']) {
            $cookie = Common::getToken();
            Cookie::set('MSPASS', $cookie, ['expire' => CommonConfig::COOKIE_EXPIRE_TIME,]);
            Cache::set($cookie, $data[0], CommonConfig::COOKIE_EXPIRE_TIME);
            return $this->getRes();
        } else {
            return $this->getRes(Error::ERR_PASSWORD);
        }
    }

    public function checkParam($param)
    {
        $rule = [
            'username' => 'require',
            'password' => 'require',
        ];
        $msg = [
            'username.require' => '账号必填',
            'password.require' => '密码必填',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }
}
